package scalab.core.utils

import scalab.core.Resource
import scalab.utils.Reporter
import java.io.FileOutputStream
import java.nio.channels.FileLock
sealed trait Lock{

	val mutex: Resource
 	
 	def acquire: FileLock = {
		//asserts that the lock can be created
		//except if privileges are missing
		//in which case an exception will be thrown
		mutex.getParentFile.mkdirs 
		val fos = new FileOutputStream(mutex)
		fos.getChannel.lock
 	}
}

object Lock{
	
	def apply(locker: Resource): FileLock = {
		val lock = create(locker)
		lock.acquire
	}

	def apply(locker: String): FileLock = apply(Resource(locker))

	private def create(locker: Resource): Lock = new Lock{
		val mutex: Resource = locker
	}
}
